class ProfileController {

  def imageService
  def authenticateService
  
  def index = { redirect(action: list, params: params) }

  // the delete, save and update actions only accept POST requests
  static allowedMethods = [delete: 'POST', save: 'POST', update: 'POST']

  def list = {
    if (!params.max) params.max = 20
    [profileInstanceList: Profile.list(params)]
  }

  def show = {
    def profileInstance = Profile.get(params.id)

    if (!profileInstance) {
      flash.message = "Profile not found with id ${params.id}"
      redirect(action: list)
    }
    else { return [profileInstance: profileInstance] }
  }

  def edit = {
    def profileInstance = Profile.get(params.id)

    if (!profileInstance || (profileInstance.user != authenticateService.userDomain() && !authenticateService.ifAllGranted(Role.ADMIN))) {
      flash.message = "Profile not found with id ${params.id} or no permission to change profile"
      redirect(action: list)
    }
    else {
      return [profileInstance: profileInstance]
    }
  }

  def update = {
    def profileInstance = Profile.get(params.id)
    if (profileInstance && (profileInstance.user == authenticateService.userDomain() || authenticateService.ifAllGranted(Role.ADMIN))) {
      if (params.version) {
        def version = params.version.toLong()
        if (profileInstance.version > version) {

          profileInstance.errors.rejectValue("version", "profile.optimistic.locking.failure", "Another user has updated this Profile while you were editing.")
          render(view: 'edit', model: [profileInstance: profileInstance])
          return
        }
      }
      try {
        def inputStream = request.getFile('photo').inputStream
        byte[] file = new byte[inputStream.available()]
        inputStream.read(file)
        profileInstance.photo = imageService.scale(file, 80, 100)
      } catch (Exception e) {
        log.error("An error occurred while updating the profile photo of ${profileInstance.user}", e)
      }
      bindData(profileInstance, params, [exclude: 'photo'])
      if (!profileInstance.hasErrors() && profileInstance.merge()) {
        flash.message = "Profile ${params.id} updated"
        redirect(action: show, id: profileInstance.id)
      }
      else {
        render(view: 'edit', model: [profileInstance: profileInstance])
      }
    }
    else {
      flash.message = "Profile not found with id ${params.id} or no permussion to change profile"
      redirect(action: edit, id: params.id)
    }
  }
}
